package cn.itsource.controller;

import cn.itsource.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
//@DefaultProperties(defaultFallback = "getUserfallBack")
// 默认认的回退方法不能有参数。
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/getUserById/{id}")
    @HystrixCommand(fallbackMethod = "getUserfallBack")
    public User getUser(@PathVariable("id")Long id){
        // 订单服务，调用 User服务获取到 User对象
        // 2020 端口号是固定的，需要负载均衡 Ribbon
        //String url = "http://localhost:2020/getUserById/"+id;
        // Ribbon 通过服务名找到 客户端列表，取出合适的客户端发送请求
        String url ="http://USER-SERVER/user/getUserById/"+id;

        // 发送请求
        return restTemplate.getForObject(url,User.class);
    }

    // 兜底方法，正常请求失败，会调用！
    public User getUserfallBack(Long id){
        log.debug("请求失败，用户服务不可用!!");
        return new User(-1L,"用户不存在","用户服务不可用");
    }
}
